﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using System.Drawing.Imaging;
using Nevron.Diagram.Extensions;
using Nevron.Diagram.WinForm.Commands;

namespace ActiveFramework.CADGraphWinFormExt
{
    class SaveToDBCommand : NSaveDrawingCommand
    {
        private string metaControlCD { get; set; }
        private bool activatedDocument { get; set; }


        private Guid id { get; set; }

        public SaveToDBCommand(string metaControlCD, Guid id, bool activatedDocument)
        {
            this.metaControlCD = metaControlCD;
            this.id = id;
            this.activatedDocument = activatedDocument;
        }

        public override void Execute()
        {
            SaveInDB();
        }

        public override bool Enabled
        {
            get
            {
                if (activatedDocument == true)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
        }
        private void SaveInDB()
        {
            System.IO.MemoryStream binaryStream = new System.IO.MemoryStream();
            System.IO.MemoryStream imageStream = new System.IO.MemoryStream();

            NPersistencyManager persistencyManager = new NPersistencyManager();
            NPersistentDocument pdoc = new NPersistentDocument();
            pdoc.Sections.Add(new NPersistentSection("Document", this.Commander.Document));
            persistencyManager.PersistentDocument = pdoc;
            persistencyManager.SaveToStream(binaryStream, Nevron.Serialization.PersistencyFormat.Binary, null);
            NImageExporter imageExporter = new NImageExporter(this.Commander.Document);
            
            Bitmap bmp = imageExporter.RenderToBitmap();
            bmp.Save(imageStream, ImageFormat.Png);

            switch (metaControlCD)
            {
                case "FRM_00084":
                    binaryStream.Position = 0;
                    SystemBoxSDK.PL.CoreSDK.SOPAttribute_PL.SaveAttributeDocument(id, System.Convert.ToBase64String(binaryStream.ToArray()), imageStream);
                    break;
                case "FRM_00007":
                    binaryStream.Position = 0;
                    SystemBoxSDK.PL.MESSDK.RoutingSheet_PL.SaveDiagramDocuments(id, binaryStream, imageStream);
                    break;
            }
        }   
    }
}
